package com.aiyige.page.interest.selectindustry;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.model.tag.Tag;
import com.aiyige.page.interest.model.Interest;
import com.aiyige.page.interest.selectuserinterest.adapter.IndustryAdapter;
import com.aiyige.page.interest.util.InterestUtil;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.RetrofitUtil;
import com.aiyige.utils.SafeAsyncTask;
import com.aiyige.utils.ToastX;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.j256.ormlite.stmt.query.In;

import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Response;

@Route(path = ARouterConfig.SelectIndustryPage)
public class SelectIndustryPage extends AppCompatActivity {
    public static final String ACTION_SELECTED_DATA = "com.aiyige.action.ACTION_SELECTED_DATA";

    @BindView(R.id.backBtn)
    ImageView backBtn;
    @BindView(R.id.titleBar)
    ConstraintLayout titleBar;
    @BindView(R.id.mainRv)
    RecyclerView mainRv;

    @Autowired
    List<Interest> data = new LinkedList<>();

    IndustryAdapter industryAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_select_industry);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        mainRv.setLayoutManager(new GridLayoutManager(this, 4));
        industryAdapter = new IndustryAdapter();
        industryAdapter.bindToRecyclerView(mainRv);
        industryAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                for (int i = 0; i < industryAdapter.getData().size(); ++i) {
                    industryAdapter.getItem(i).setSelected(i == position);
                }
                industryAdapter.notifyDataSetChanged();
                Intent data = new Intent();
                data.putExtra(ACTION_SELECTED_DATA, industryAdapter.getItem(position));
                setResult(RESULT_OK, data);
                finish();
            }
        });
        requestData();
    }

    public void requestData() {
        new RequestDataTask(this).execute();
    }

    public class RequestDataTask extends SafeAsyncTask<Object, Object, Object> {
        List<Interest> industryList = new LinkedList<>();

        public RequestDataTask(Activity activity) {
            super(activity, R.string.loading);
        }

        @Override
        public void safeOnPostExecute(Object o) {
            if (o instanceof Exception) {
                ToastX.show((Exception) o);
            } else {
                industryAdapter.setNewData(industryList);
            }
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                Response<ResponseBody> response = ApiManager.getService().recommendIndustry().execute();
                if (response.code() != ResponseCode.OK) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                String json = RetrofitUtil.getResponseBodyAsString(response);
                List<Tag> tagList = JSON.parseArray(json, Tag.class);
                industryList.addAll(InterestUtil.convertTagListToInterestList(tagList));
                InterestUtil.resumeSelect(industryList, data);
                for (Interest interest : industryList) {
                    interest.setRecommend(false);
                }
                return null;
            } catch (Exception e) {
                return e;
            }
        }
    }


    @OnClick({R.id.backBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.backBtn:
                setResult(RESULT_CANCELED);
                finish();
                break;
        }
    }
}
